package com.zf.wms.business.datasources;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;

/**
 * @Description: 配置多数据源
 * @Author: Mine
 * @CreateDate: 2019/2/28 10:17
 * @email 1943511692@qq.com
 * @Version: 1.0.0
 */
@Configuration
public class DynamicDataSourceConfig {

    @Bean
    @ConfigurationProperties("spring.datasource.druid.first")
    public DataSource firstDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @ConfigurationProperties("spring.datasource.druid.second")
    public DataSource secondDataSource(){
        return DruidDataSourceBuilder.create().build();
    }

    @Bean
    @Primary
    public DynamicDataSource dataSource(DataSource firstDataSource, DataSource secondDataSource) {
        Map<DatasourceTypeEnum, DataSource> targetDataSources = new HashMap<>();
        targetDataSources.put(DatasourceTypeEnum.DEFAULT_SOURCE, firstDataSource);
        targetDataSources.put(DatasourceTypeEnum.OTHER_SOURCE, secondDataSource);
        return new DynamicDataSource(firstDataSource, targetDataSources);
    }
}
